package TimerInstance;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private long time;
    private Runnable runnable;
    public MyTimerTask (Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time-o.time);
    }

    public long getTime() {
        return time;
    }
}

// 定时器
class MyTimer {
    private Thread t = null;
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue();

    Object locker = new Object();


    public void schedule(Runnable runnable,long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.offer(task);
            locker.notify();
        }
    }

    public void cancel() {
        t.interrupt();
    }

    public MyTimer() {
        t = new Thread(() -> {
            while (!t.isInterrupted()) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {
                            queue.poll();
                            task.run();
                        } else {
                            locker.wait(task.getTime()-curTime);
                        }
                    }
                }catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t.start();
    }
}


public class MyTimerInstance {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("Running after 1000ms");
            }
        },1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("Running after 2000ms");
            }
        },2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("Running after 3000ms");
                timer.cancel();
            }
        },3000);

        System.out.println("First line");
    }
}
